package com.ljt.utils;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class StringUtils {

    private static final String COMMA_SEPARATOR = ",";
    private static final String DEFAULT_CHARSET_NAME = "UTF-8";
    private static final DecimalFormat intDF = new DecimalFormat("0"); 
    
    public static String deleteOne(String origin, String sub) {
        int begin = origin.indexOf(sub);
        if (begin == -1)
            return origin;

        String result = origin.substring(0, begin) + origin.substring(begin + sub.length(), origin.length());
        return result;
    }

    public static boolean contains(String str, String match) {
        for (int i = 0; i < match.length(); i++) {
            if (str.indexOf(match.charAt(i)) != -1) {
                return true;
            }
        }
        return false;
    }

    public static String arrayToString(Long... arr) {
        String str = "";
        if (arr == null || arr.length == 0)
            return str;
        StringBuffer sb = new StringBuffer();
        for (Long element : arr) {
            sb.append(element);
            sb.append(COMMA_SEPARATOR);
        }
        str = sb.toString();
        int index = str.lastIndexOf(COMMA_SEPARATOR);
        return str.substring(0, index);
    }

    public static String arrayToString(String... arr) {
        String str = null;
        if (arr == null || arr.length == 0)
            return "";
        StringBuffer sb = new StringBuffer();
        for (String element : arr) {
            sb.append(element);
            sb.append(COMMA_SEPARATOR);
        }
        str = sb.toString();
        int index = str.lastIndexOf(COMMA_SEPARATOR);
        return str.substring(0, index);
    }

    public static String[] stringToArray(String str) {
        String[] arr = new String[0];
        if (str != null && !str.trim().equals(""))
            arr = str.split(COMMA_SEPARATOR);
        return arr;
    }

    public static String filtrateString(String resStr, String delStr) {
        String str = null;
        if (resStr == null || delStr == null || resStr.trim().equals("") || delStr.trim().equals(""))
            return str;
        String[] arr = resStr.split(COMMA_SEPARATOR);
        StringBuffer sb = new StringBuffer();
        for (String element : arr) {
            if (!element.equals(delStr)) {
                sb.append(element);
                sb.append(COMMA_SEPARATOR);
            }
        }
        str = sb.toString();
        int index = str.lastIndexOf(COMMA_SEPARATOR);
        if (index == -1)
            return "";
        return str.substring(0, index);
    }

    public static String addString(String resStr, String addStr) {
        if (null == resStr || "".equals(resStr)) {
            return addStr;
        }
        return resStr + COMMA_SEPARATOR + addStr;
    }

    public static boolean hasString(String resSts, String hasStr) {
        if (null == resSts || "".equals(resSts)) {
            return false;
        }
        resSts = COMMA_SEPARATOR + resSts + COMMA_SEPARATOR;
        if (resSts.indexOf(COMMA_SEPARATOR + hasStr + COMMA_SEPARATOR) > -1) {
            return true;
        }
        return false;

    }

    public static String mysqlEscape(String str) {
        if (str == null)
            return "";
        return str.replace("\\", "\\\\").replace("'", "\\'").replace("\"", "\\\"");
    }

    public static String tlogEscape(String str) {
        if (str == null)
            return "";
        return str.replace("|", "丨");
    }

    public static String nameEscape(String str) {
        if (str == null)
            return "";
        return str.replace("$", "﹩");
    }

    // public static String tradChar(String src, Integer length) {
    // if(isEmpty(src)) return src;
    // StringBuilder sb = new StringBuilder();
    // char[] arr = HtmlUtil.htmlUnEscape(src).toCharArray();
    // for(char c : arr){
    // if(isGBK(c))
    // length = length - 2;
    // else
    // length = length - 1;
    // if(length>=0)
    // sb.append(c);
    // else
    // break;
    // }
    // return sb.toString();
    // }

    public static boolean isGBK(char c) {
        String regEx = "[\\u4e00-\\u9fa5]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(String.valueOf(c));
        return m.find();
    }

    public static boolean isEmpty(String src) {
        if (null == src)
            return true;
        if (src.trim().equals(""))
            return true;
        if (src.trim().equalsIgnoreCase("null"))
            return true;
        return false;
    }

    public static int[] parseIntArray(String[] strs) {
        try {
            int[] result = new int[strs.length];
            for (int i = 0; i < strs.length; i++) {
                result[i] = Integer.parseInt(strs[i]);
            }
            return result;
        } catch (Exception e) {
        }
        return new int[0];
    }

    public static String getUTF8Str(String str) {
        try {
            return new String(str.getBytes("UTF-8"), "UTF-8");
        } catch (Exception e) {
            return str;
        }
    }

    public static String getGBKStr(String str, String encoding) {
        try {
            return new String(str.getBytes(encoding), "GBK");
        } catch (Exception e) {
            return str;
        }
    }

    public static String getUTF8Str(String str, String encoding) {
        try {
            return new String(str.getBytes(encoding), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            return str;
        }
    }

    public static int getLength(String str) {
        if (str == null)
            return 0;
        int len = 0;
        // for (int i = 0; i < str.length(); i++)
        // {
        // char c = str.charAt(i);
        // int k = c;
        // Logger.getLogger(StringUtil.class).error(k);
        // if (k > 256)
        // {
        // len += 2;
        // }
        // else
        // {
        // len += 1;
        // }
        // }
        char[] charArray = str.toCharArray();
        for (int i = 0; i < charArray.length; i++) {
            char tempchar = charArray[i];
            if (Character.getType(tempchar) == Character.OTHER_LETTER) {
                len += 2;
            } else {
                len += 1;
            }
        }
        return len;
    }

    public static String splitString(String str, int num) {

        // Logger.getLogger(StringUtil.class).error("split:"+str+" to "+num);
        //
        if (str == null || getLength(str) <= num)
            return str;

        char[] charArray = str.toCharArray();
        String subStr = "";
        int index = 0;
        for (int i = 0, j = 0; i < num;) {
            if (j >= charArray.length)
                break;

            char tempchar = charArray[j];
            if (Character.getType(tempchar) == Character.OTHER_LETTER) {
                // 如果这个字符是一个汉字
                i = i + 2;
                if (i > num) {
                    // 如果num正好截取到半个汉字的时候，跳过此次for循环。
                    // 如果num正好截取到一个完整的汉字的时候，继续执行下面的index++等语句。
                    if (i == (num + 1)) {
                        continue;
                    }
                }
            } else {
                i++;
            }
            index++;
            j++;
        }
        subStr = str.substring(0, index);
        return subStr;
    }

    @SuppressWarnings("rawtypes")
    public static String join(String joiner, List objsvec) {
        if (objsvec == null)
            return "";
        return join(joiner, objsvec.toArray());
    }

    public static String join(String sep, Set<Object> set) {
        StringBuilder sb = new StringBuilder();
        for (Object o : set) {
            sb.append(sep);
            sb.append(o.toString());
        }

        return sb.substring(1, sb.length());
    }

    // public static String join(String sep, Long[] objs)
    // {
    // StringBuilder sb = new StringBuilder();
    // for (int i = 0; i < objs.length; i++)
    // {
    // sb.append(objs[i]);
    // if (i != objs.length - 1)
    // {
    // sb.append(sep);
    // }
    // }
    // return sb.toString();
    // }

    public static String join(String sep, Object... objs) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < objs.length; i++) {
            sb.append(objs[i]);
            if (i != objs.length - 1) {
                sb.append(sep);
            }
        }
        return sb.toString();
    }

    public static String join(String sep, String[] objs) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < objs.length; i++) {
            sb.append(objs[i]);
            if (i != objs.length - 1) {
                sb.append(sep);
            }
        }
        return sb.toString();
    }

    /**
     * 字符串变量格式
     */
    private static Pattern argPattern = Pattern.compile("\\{\\d\\}");

    /**
     * 替换字符串中的变量，变量以{1},{2}方式体现，数字使用自然数
     * 
     * @param src
     *            需要替换的字符串
     * @param refs
     *            替换后的内容
     * @return 替换后的字符串
     * @throws IllegalArgumentException
     *             有变量未被替换时抛出
     */
    public static String replaceArgs(String src, Object... refs) {
        for (int i = 0; i < refs.length; i++) {
            if (src.indexOf("{" + (i + 1) + "}") < 0) {
                // TODO 变量值比变量多
            }
            src = src.replace("{" + (i + 1) + "}", refs[i].toString());
        }
        Matcher matcher = argPattern.matcher(src);
        StringBuilder sb = new StringBuilder();
        while (matcher.find()) {
            sb.append(matcher.group()).append(", ");
        }
        if (sb.length() > 0) {
            // 变量比变量值多
            sb.append(" do not replaced in \"").append(src).append("\"");
            throw new IllegalArgumentException(sb.toString());
        }
        return src;
    }

    public static long parseScheduleTimer(String timerString) {
        // example 10y2M1d12h3m2s == 10年2个月1天12小时3分钟2秒
        String patternString = "(((\\d+)(d))?((\\d+)(h))?((\\d+)(m))?((\\d+)(s))?)*";

        Pattern pattern = Pattern.compile(patternString);

        Matcher matcher = pattern.matcher(timerString);
        int groupIndex = 3;
        long timer = 0;
        /*
         * if (matcher.find()) { for (int i = 0; i < 4; i++) { if
         * (matcher.group(groupIndex) != null) { int count =
         * Integer.valueOf(matcher.group(groupIndex)); String unit =
         * matcher.group(groupIndex + 1);
         * 
         * if ("d".equals(unit)) timer += TimeUnit.DAYS.toMillis(count); else if
         * ("h".equals(unit)) timer += TimeUnit.HOURS.toMillis(count); else if
         * ("m".equals(unit)) timer += TimeUnit.MINUTES.toMillis(count); else if
         * ("s".equals(unit)) timer += TimeUnit.SECONDS.toMillis(count); }
         * groupIndex += 3; } }
         */
        if (matcher.find()) {
            // System.out.println(matcher.group());
            for (int i = 0; i < 4; i++) {
                if (matcher.group(groupIndex) != null) {
                    int count = Integer.valueOf(matcher.group(groupIndex));
                    String unit = matcher.group(groupIndex + 1);
                    if ("d".equals(unit))
                        timer += TimeUnit.DAYS.toMillis(count);
                    else if ("h".equals(unit))
                        timer += TimeUnit.HOURS.toMillis(count);
                    else if ("m".equals(unit))
                        timer += TimeUnit.MINUTES.toMillis(count);
                    else if ("s".equals(unit))
                        timer += TimeUnit.SECONDS.toMillis(count);
                }
                groupIndex += 3;
            }
        }
        return timer;
    }

    /**
     * 过滤超过3字节的UTF8字符
     * 
     * @param text
     *            String
     * @return String
     */
    public static String filterOffUTF8MB4(String text) {
        try {
            byte[] bytes = text.getBytes("UTF-8");

            ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
            int i = 0;
            while (i < bytes.length) {
                short b = bytes[i];
                if (b > 0) {
                    buffer.put(bytes[i++]);
                    continue;
                }
                b += 256;
                if ((b ^ 0xC0) >> 4 == 0) {
                    buffer.put(bytes, i, 2);
                    i += 2;
                } else if ((b ^ 0xE0) >> 4 == 0) {
                    buffer.put(bytes, i, 3);
                    i += 3;
                } else if ((b ^ 0xF0) >> 4 == 0) {
                    i += 4;
                }
            }
            buffer.flip();
            return new String(buffer.array(), DEFAULT_CHARSET_NAME);
        } catch (UnsupportedEncodingException ex) {
            return text;
        }
    }

    public static String replaceTextScript(String text) {
        StringBuilder sb = new StringBuilder();
        int i = 0;
        while (i < text.length()) {
            if (text.charAt(i) == '$') {
                i++;
                String tmp = text.substring(i);
                System.out.println("tmp:" + tmp);
                // it's a link
                if (tmp.startsWith("l")) {

                    int idx = tmp.indexOf("$z");
                    if (idx > 0) {

                        tmp = tmp.substring(1, idx);
                        i += 1 + tmp.length() + "$z".length();
                        System.out.println("real tmp : " + tmp);
                        String url = tmp.substring(0, tmp.indexOf("$"));
                        String t1 = tmp.substring(tmp.lastIndexOf("$") + 1, tmp.length());
                        System.out.println("URL:" + url);
                        System.out.println("desc:" + t1);
                        sb.append("<a href=\"").append(url).append("\">").append(t1).append("</a>");

                    } else {
                        throw new IllegalArgumentException("input text error, script format error :" + text);
                    }
                } else if (tmp.startsWith("i")) {
                    int found = 0;
                    while (i < text.length()) {
                        if (text.charAt(i++) == '$')
                            found++;
                        if (found == 3)
                            break;
                    }
                    if (found != 3) {
                        throw new IllegalArgumentException("input text error, script format error :" + text);
                    }
                } else if (tmp.startsWith("t")) {

                    int idx = tmp.indexOf("$z");
                    if (idx > 0) {

                        tmp = tmp.substring(1, idx);
                        i += 1 + tmp.length() + "$z".length();
                        String tt = tmp.substring(tmp.indexOf("$") + 1, tmp.length());
                        System.out.println(tt);
                        sb.append(tt);
                    } else {
                        throw new IllegalArgumentException("input text error, script format error :" + text);
                    }
                }
            } else {
                sb.append(text.charAt(i));
                i++;
            }
        }

        return sb.toString();
    }
    
    public static String[] splitFileName(String filename)
    {
    	String[] str = new String[2];
    	int lastIndex = filename.lastIndexOf(".");
    	if(lastIndex>=0)
    	{
    		str[0] = filename.substring(0, lastIndex);
    		str[1] = filename.substring(lastIndex+1, filename.length());
    	}else
    	{
    		str[0] = filename;
    		str[1] = "";
    	}
    	return str;
    	
    }
    
    
    public static String getLoginMsg(String username, String passwd)
    {
    	
    	if(username == null || passwd == null)
    		return null;
    	StringBuffer sb = new StringBuffer();
    	username = username.toLowerCase();
    	sb.append(username.substring(0,1)).append(passwd.substring(0,2)).append(username.substring(1, 2)).append(passwd.substring(2, 6)).append(username.substring(2,4)).append(passwd.substring(6, passwd.length())).append(username.substring(4, username.length()));
    	return sb.toString();
    }

    /**
     * 生成手机验证码(短信认证用)
     * @return
     */
    public static String phoneRandom(){
     //变量
	 boolean numberFlag=true;//true 纯数字 ；false 数字+字母
	 int length=6;//长度
	
     String retStr = "";
     String strTable = numberFlag ? "1234567890" : "1234567890abcdefghijkmnpqrstuvwxyz";
     int len = strTable.length();
     boolean bDone = true;
     do {
      retStr = "";
      int count = 0;
      for (int i = 0; i < length; i++) {
       double dblR = Math.random() * len;
       int intR = (int) Math.floor(dblR);
       char c = strTable.charAt(intR);
       if (('0' <= c) && (c <= '9')) {
        count++;
       }
       retStr += strTable.charAt(intR);
      }
      if (count >= 2) {
       bDone = false;
      }
     } while (bDone);

     return retStr;
    }
    
    public static String parseNumber(Number num)
    {
    	return intDF.format(num);
    }
    
    public static void main(String[] args) throws Exception {
        // int len = StringUtil.getLength("C:\\疑问\\新流程.png");
        // System.out.println(len);
        // String splited = StringUtil.splitString("C:\\疑问\\新流程.png", 17);
        // System.out.println(splited);
        // System.out.println(StringUtil.join("_", 123, new
        // Timestamp(System.currentTimeMillis())));
        //
        // long timer = StringUtil.parseScheduleTimer("1d3m2s1h");
        // System.out.println("timer:" + timer);

        // String tmp =
        // StringUtil.replaceTextScript("大家好，其实这个真不错，试试呢？$lhttp://www.baidu.com$0$1234$百度$z$iabc$0$0$$t232$谷歌$z试试这个吧");
        // System.out.println(tmp);
    	/*String[] str = splitFileName(".jpg");
    	System.out.println(str[0]);
    	System.out.println(str[1]);
    	
    	System.out.println(getEncryptedLoginMsg("jq520", "123456",2214437893177481L));
    	System.out.println(URLEncoder.encode("/contract/reseller?cid=3","utf-8"));*/
//    	Map<String,String> map=new HashMap<String, String>();
//    
////    	System.out.println(phoneRandom());
////    	System.out.println("/contract/reseller?cid=3".split("\\?")[0]);
//    	System.out.println(parseNumber(123232.22));
//    	System.out.println(parseNumber(12323));
//    	System.out.println(parseNumber(-123232.22));
//    	System.out.println(parseNumber(0));
//    	
    	System.out.println(getRandomNum(6));
    	
    }
    /**
     * 获取num位的重复随机码
     * 纯数字
     * @param num
     * @return
     */
    public static String getRandomNum(int num){
    	Random random=new Random();
    	StringBuffer buf=new StringBuffer();
    	for(int i=0;i<num;i++){
    		buf.append(random.nextInt(9));
    	}
    	return buf.toString();
    }


    
}
